"""
数据库升级脚本，应用最新的数据库迁移
"""
import os
import sys
import sqlite3
from sqlalchemy import create_engine, text

# 将项目根目录添加到Python路径
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
sys.path.insert(0, project_root)

def add_column_if_not_exists(conn, table_name, column_name, column_type):
    """检查列是否存在，如果不存在则添加"""
    cursor = conn.cursor()
    cursor.execute(f"PRAGMA table_info({table_name})")
    columns = [info[1] for info in cursor.fetchall()]
    
    if column_name not in columns:
        cursor.execute(f"ALTER TABLE {table_name} ADD COLUMN {column_name} {column_type}")
        print(f"已添加{column_name}列到{table_name}表")
        return True
    else:
        print(f"{column_name}列已存在于{table_name}表中")
        return False

def main():
    # 数据库路径
    db_path = os.path.join(project_root, 'backend', 'twrpa.db')
    
    if not os.path.exists(db_path):
        print(f"错误：数据库文件不存在：{db_path}")
        return
    
    try:
        # 使用SQLite连接直接修改数据库
        conn = sqlite3.connect(db_path)
        
        # 添加cleaned_name列到item_sku表
        added = add_column_if_not_exists(conn, 'item_sku', 'cleaned_name', 'TEXT')
        
        # 提交更改
        conn.commit()
        conn.close()
        
        if added:
            print("数据库升级成功！")
        else:
            print("数据库已是最新版本，无需升级。")
        
    except Exception as e:
        print(f"升级数据库时出错：{str(e)}")

if __name__ == "__main__":
    main() 